document.addEventListener('DOMContentLoaded', () => {
    const questionInput = document.getElementById('question-input');
    const submitBtn = document.getElementById('submit-btn');
    const exportBtn = document.getElementById('export-btn');
    const chatHistory = document.getElementById('chat-history');

    // 发送问题
    const sendQuestion = async () => {
        const question = questionInput.value.trim();
        if (!question) return;

        // 添加用户消息到历史记录
        addMessageToHistory('user', question);
        questionInput.value = '';

        // 添加正在思考提示
        const thinkingMessageId = addThinkingMessage();

        try {
            // 发送请求到后端
            const response = await fetch('/api/ask', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ question }),
            });

            // 移除正在思考提示
            removeThinkingMessage(thinkingMessageId);

            if (!response.ok) {
                throw new Error('请求失败');
            }

            const data = await response.json();

            // 添加AI回答到历史记录
            addMessageToHistory('bot', data.answer);
        } catch (error) {
            // 移除正在思考提示
            removeThinkingMessage(thinkingMessageId);

            // 添加错误消息
            addMessageToHistory('bot', `抱歉，处理请求时出错: ${error.message}`);
        }
    };

    // 添加消息到历史记录
    const addMessageToHistory = (role, content) => {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${role}-message`;

        const contentDiv = document.createElement('div');
        contentDiv.className = 'message-content';

        // 如果是AI消息，结构化显示
        if (role === 'bot') {
            contentDiv.innerHTML = formatBotResponse(content);
        } else {
            contentDiv.textContent = content;
        }

        const metaDiv = document.createElement('div');
        metaDiv.className = 'message-meta';
        metaDiv.textContent = new Date().toLocaleTimeString();

        messageDiv.appendChild(contentDiv);
        messageDiv.appendChild(metaDiv);

        chatHistory.appendChild(messageDiv);
        chatHistory.scrollTop = chatHistory.scrollHeight;

        return messageDiv.id;
    };

    // 格式化AI响应
    const formatBotResponse = (content) => {
        // 简单处理换行，实际应用中可以根据响应格式进行更复杂的解析
        return content
            .replace(/\n/g, '<br>')
            .replace(/### (.*?)<br>/g, '<h3>$1</h3>')
            .replace(/\* (.*?)<br>/g, '<li>$1</li>')
            .replace(/<li>/g, '<ul><li>')
            .replace(/<\/li>(?!<li>)/g, '</li></ul>');
    };

    // 添加正在思考消息
    const addThinkingMessage = () => {
        const messageDiv = document.createElement('div');
        messageDiv.id = 'thinking-message-' + Date.now();
        messageDiv.className = 'message bot-message thinking-message';

        const contentDiv = document.createElement('div');
        contentDiv.className = 'message-content';
        contentDiv.innerHTML = '<div class="typing-indicator"><span></span><span></span><span></span></div>';

        messageDiv.appendChild(contentDiv);
        chatHistory.appendChild(messageDiv);
        chatHistory.scrollTop = chatHistory.scrollHeight;

        return messageDiv.id;
    };

    // 移除正在思考消息
    const removeThinkingMessage = (id) => {
        const thinkingMessage = document.getElementById(id);
        if (thinkingMessage) {
            thinkingMessage.remove();
        }
    };

    // 导出报告
    const exportReport = async () => {
        try {
            const response = await fetch('/api/export', {
                method: 'GET',
            });

            if (!response.ok) {
                throw new Error('导出失败');
            }

            const blob = await response.blob();
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `rag_qa_${new Date().toISOString().slice(0,10)}.docx`;
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
        } catch (error) {
            addMessageToHistory('bot', `导出报告时出错: ${error.message}`);
        }
    };

    // 事件监听
    submitBtn.addEventListener('click', sendQuestion);
    questionInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            sendQuestion();
        }
    });
    exportBtn.addEventListener('click', exportReport);
});